package com.aismy.admin.service.impl;

import com.aismy.admin.service.FileService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Aismy
 * @date 2025/03/14
 **/
@Service
public class LocalFileServiceImpl implements FileService {
    private static final String BASE_PATH = new File("").getAbsolutePath() + "\\backend\\admin\\src\\main\\resources\\static\\file\\";

    private static final String BASE_URL = "http://localhost:8080/api/file/download/";

    @Override
    public String uploadFile(MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 生成文件名
        String newFileName = System.currentTimeMillis() + "_" + RandomStringUtils.randomAlphabetic(8) + suffix;
        // 文件保存路径
        String filePath = BASE_PATH + newFileName;
        // 保存文件
        try {
            Files.copy(file.getInputStream(), Paths.get(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return BASE_URL + newFileName;
    }

    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        Path filePath = Paths.get(BASE_PATH, fileName);
        if (!Files.exists(filePath)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode(fileName, "UTF-8"));

        // 复制文件到响应输出流
        try (InputStream in = Files.newInputStream(filePath)) {
            FileCopyUtils.copy(in, response.getOutputStream());
        }
    }

    @Override
    public String getFileUrl(String fileName) {
        return "";
    }

}
